#ifdef WIN32
#include "SDL.h"
#else
#include <SDL/SDL.h>
#endif

#include "gamekit/Game.h"
#include "gamekit/Scene.h"
#include "gamekit/Window.h"

#include "gamekit/sdl/SDLWindow.h"

using namespace gamekit;

Game::Game(const std::string& title, const ushort& width, const ushort& height, const uint& depth)
	: m_run(false)
{
	m_window = new sdl::SDLWindow(title, width, height, depth);
	m_window->addEventHandler(&gamekit::Game::onQuit, this);

	m_scene = new Scene(this);
}

Game::~Game()
{
}

void Game::init(void)
{
	m_window->init();
	m_scene->init();

	m_previousTicks = SDL_GetTicks();
	m_run = true;
}

void Game::onQuit(const EventArgs<Window, WindowEvents, weQuit>& args)
{
}

uint Game::elapsed(void)
{
	uint current = SDL_GetTicks();
	uint elapsed = current - m_previousTicks;
	m_previousTicks = current;

	return elapsed;
}

void Game::loop(void)
{
	while(m_run)
	{
		uint elapsed = this->elapsed();

		processEvents();

		m_scene->update(elapsed);

		m_window->beginDraw();
		m_scene->draw(elapsed);
		m_window->endDraw();

		SDL_Delay(10);
	}
}

void Game::processEvents(void)
{
	SDL_Event event;
	while (SDL_PollEvent(&event))
	{
		switch(event.type)
		{
		case SDL_QUIT:
			{
				quit();
			}
			break;
		}
	}
}

SafePointer<Scene> Game::scene(void) const
{
	return SafePointer<Scene>(m_scene);
}

SafePointer<Window> Game::window(void) const
{
	return SafePointer<Window>(m_window);
}

void Game::quit(void)
{
	m_run = false;
}

